package com.ttx.pattern.example.chain.tomcat.filterchain;

import com.ttx.pattern.example.chain.tomcat.servlet.ServletException;
import com.ttx.pattern.example.chain.tomcat.servlet.ServletRequest;
import com.ttx.pattern.example.chain.tomcat.servlet.ServletResponse;

import java.util.ArrayList;
import java.util.List;

/**
 * @author TimFruit
 * @date 19-5-12 上午8:54
 */
public class AppFilterChain implements FilterChain {

    //[warning] tomcat源码中是数组形式(AppFilterConfig[])
    //这里为方便使用,所以使用了arrayList
    private List<AppFilterConfig> appFilterConfigs=new ArrayList<>();

    // 过滤器链调用的的标识
    private int pos=0;


    public AppFilterChain() {
    }


    public void addAppFilterConfig(AppFilterConfig filterConfig){
        appFilterConfigs.add(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response) {
        //do other ...
        internalDoFilter(request, response);
    }

    private void internalDoFilter(ServletRequest request, ServletResponse response){
        if(pos<appFilterConfigs.size()) {
            AppFilterConfig appFilterConfig = appFilterConfigs.get(pos);
            pos++;

            Filter filter;
            try {
                filter = appFilterConfig.getFilter();
            } catch (ClassNotFoundException | IllegalAccessException | InstantiationException e) {
                throw new ServletException("获取过滤器出错", e);
            }

            filter.doFilter(request, response, this);
        }
    }


    /**
     * 重新使用
     */
    void reuse(){
        pos=0;
    }
}
